<template>
  <BasicModal
    v-bind="$attrs"
    :width="modalWidth"
    @register="registerModal"
    :title="getTitle"
    @ok="handleOK"
  >
    <div style="display: flex">
      <Card
        :tab-list="tabListTitle"
        v-bind="$attrs"
        :active-tab-key="activeKey"
        @tab-change="onTabChange"
      >
        <BasicForm @register="registerForm" v-if="activeKey == t('sys.informaionMatchaing.columns.match')" />

        <BasicForm @register="registerFormpositon" v-else>
          <template #colSlot_field5="{ model, field, disabled }">
            <FormItem
              :name="field"
              label="关键字"
              :rules="[{ required: true }]"
              :labelCol="{ span: 5 }"
            >
              <a-input v-model:value="model[field]" :disabled="disabled" placeholder="关键字" />
            </FormItem>
          </template>
        </BasicForm>
        <div v-if="activeKey == t('sys.informaionMatchaing.columns.orientation')">
          <Button
            type="primary"
            style="margin-left: 30px; margin-top: 10px"
            @click="onSearch('keyword')"
            >生成关键字</Button
          >

          <Button type="primary" style="margin-left: 30px; margin-top: 5px" @click="onSearch"
            >生成提示词</Button
          >
        </div>
        <div v-if="tips">
          <div style="margin: 10px 0 0 10px; font-weight: bold">提示词</div>
          <div style="margin-left: 20px; margin-top: 10px">
            <a-textarea v-model:value="tips" :autoSize="{ minRows: 5, maxRows: 6 }" />
          </div>
        </div>
      </Card>

      <div style="width: 100%" v-if="(KeyWord.length > 0 || tips) && activeKey == t('sys.informaionMatchaing.columns.orientation')">
        <div v-if="KeyWord.length > 0">
          <span style="margin-left: 10px; font-weight: bold">关键字</span>
          <div style="margin-left: 20px">
            <div
              v-for="(item, index) in KeyWord"
              :key="index"
              style="margin-top: 10px; display: flex"
            >
              <a-input v-model:value="KeyWord[index]" placeholder="关键字" />
              <div style="margin: 0 20px">
                <InputNumber
                id="inputNumber"
                defaultValue="0"
                autofocus
                v-model:value="value"
                :min="1"
                :max="100"
                placeholder="权重"
              />
              </div>
             
              <Icon
                icon="ant-design:close-circle-outlined"
                @click="delkeyWord(index)"
                :size="30"
                v-if="index != KeyWord.length - 1"
                style="margin-left: 5px"
              />
              <Icon
                icon="ant-design:plus-circle-outlined"
                @click="addkeyWord"
                :size="30"
                v-if="index == KeyWord.length - 1"
                style="margin-left: 5px"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { onMounted } from 'vue';
  import { Steps, Card, FormItem, Button, message, InputNumber } from 'ant-design-vue';
  import Icon from '@/components/Icon/Icon.vue';
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import axios from 'axios';
  import { matchCategory } from '@/api/demo/InformationMatching'; // 假设 matchCategory 接口在这里
  import { accountFormSchema, accountFormSchemapositon } from './account.data';
  import { AddTaskpageListAPI } from '@/api/demo/InformationMatching';
  import AButton from '@/components/VxeTable/src/components/AButton';
  import { useI18n } from "@/hooks/web/useI18n";

  const { t } = useI18n();
  const value=ref(0)
  const emit = defineEmits(['success']);
  defineOptions({ name: 'AccountModal' });
  const isUpdate = ref(true);
  const rowId = ref('');
  const modalWidth = ref('50%');
  const activeKey = ref(t('sys.informaionMatchaing.columns.match'));
  const KeyWord = ref<string[]>([]);
  const tips = ref('');
  const tabListTitle = [
    {
      key: t('sys.informaionMatchaing.columns.match'),
      tab: t('sys.informaionMatchaing.columns.match'),
    },
    {
      key: t('sys.informaionMatchaing.columns.orientation'),
      tab: t('sys.informaionMatchaing.columns.orientation'),
    },
  ];
  const [registerForm, { resetFields, setFieldsValue, updateSchema, getFieldsValue }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: accountFormSchema,
    showActionButtonGroup: false,
  });
  const [
    registerFormpositon,
    { getFieldsValue: getFieldsValuePosi, updateSchema: updateSchemaPo },
  ] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: accountFormSchemapositon,
    showActionButtonGroup: false,
  });
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    await resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      rowId.value = data.record.id;
      setFieldsValue({
        ...data.record,
      });
    }

    const categoryData = await matchCategory();
    // 更新 accountFormSchema 中的 MatchingType 值
    updateSchema({
      field: 'category',
      componentProps: { options: categoryData.data },
    });

    updateSchemaPo({
      field: 'category',
      componentProps: { options: categoryData.data },
    });
  });
  const getTitle = computed(() => (!unref(isUpdate) ? t('sys.configuration.add') : t('sys.configuration.edit')));

  async function handleOK() {
    let params = {};

    if (activeKey.value == t('sys.informaionMatchaing.columns.match')) {
      params = { ...getFieldsValue(), type: 'match' };
      const data = await AddTaskpageListAPI(params);
      emit('success', data); // 触发 success 事件
      closeModal();
    } else {
      if (KeyWord.value.length > 0) {
        const keyWordString = KeyWord.value.join(','); // 将数组转换为字符串
        params = {
          ...getFieldsValuePosi(),
          keyWord: keyWordString,
          type: 'orientation',
          callword: tips.value,
        };
        const data = await AddTaskpageListAPI(params);
        emit('success', data); // 触发 success 事件
        closeModal();
      } else {
        message.error('请先生成关键字');
      }
    }
  }
  async function onTabChange(key) {
    activeKey.value = key;
    const categoryData = await matchCategory();
    // 更新 accountFormSchema 中的 MatchingType 值
    updateSchema({
      field: 'category',
      componentProps: { options: categoryData.data },
    });

    updateSchemaPo({
      field: 'category',
      componentProps: { options: categoryData.data },
    });
  }
  function delkeyWord(index: number) {
    KeyWord.value.splice(index, 1);
  }

  function addkeyWord() {
    KeyWord.value.push('');
  }

  async function fetchKeywords(params) {
    //本地 http://192.168.0.109:6001
    //线上 http://8.136.118.105:6001
    try {
      const response = await axios.get('http://8.136.118.105:6001/getWords', {
        params,
      });

      if (response.data.data != 'None') {
        KeyWord.value = response.data.data.split(',');
      }
      return response.data;
    } catch (error) {
      message.error('生成关键字失败');
      return null;
    }
  }

  async function fetchKeytips(params) {
    //本地 http://192.168.0.109:6001
    //线上 http://8.136.118.105:6001
    try {
      const response = await axios.get('http://8.136.118.105:6001/getTips', {
        params,
      });

      tips.value = response.data.data;

      return response.data;
    } catch (error) {
      message.error('生成提示词');
      return null;
    }
  }

  async function onSearch(value) {
    let Data = { ...getFieldsValuePosi() };
    if (value == 'keyword') {
      let params = {
        content: Data.remark,
      };
      const data = await fetchKeywords(params);
      if (data) {
        message.success('生成关键字成功');
      }
    } else {
      let params = {
        content: Data.remark,
        title: Data.title,
      };
      const data = await fetchKeytips(params);
      if (data) {
        message.success('生成提示词成功');
      }
    }
  }

  async function onSubmit() {
    if (tips.value.trim() === '') {
      message.error('提示词不能为空');
      return;
    }
    let Data = { ...getFieldsValuePosi() };
    let params = {
      tips: tips.value,
      content: Data.remark,
    };
    const data = await fetchKeywords(params);
    if (data) {
      message.success(t('sys.configuration.succesSubmit'));
    } else {
      message.error('提交失败');
    }
  }
</script>
